<!doctype html>

<html>
  <head>
    <title>Ethereum Demo</title>
      <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">

</script><script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
<script src="https://cdn.bootcss.com/vConsole/3.3.2/vconsole.min.js"></script>
<script>
  var vConsole = new VConsole();
  console.log('Hello world');
</script>

  </head>

  <body>
    <div class="jumbotron jumbotron-fluid">
      <div class="container">
        <h1 class="display-5">JS Ethereum Signature Example</h1>
        <p class="lead">Simple signature examples for use with <a href="https://www.metamask.io"> MetaMask </a> and <a href="https://trustwallet.com">Trust</a></p>
      </div>
    </div>
    <div class="container">
      <div class="row border-bottom" >
          <div class="col-6">
            <h5>Connect</h5>
          </div>
            <div class="col-6">
              <button type="button" class="btn btn-dark" id="connectButton">Connect</button>
            </div>
        </div>
      <div class="row border-bottom" >
        <div class="col-6">
          <h5>Eth_Sign</h5>
        </div>
        <div class="col-6">
          <button type="button" class="btn btn-dark" id="ethSignButton">eth_sign</button>
        </div>
      </div>
      <div class="row border-bottom" >
        <div class="col-6">
          <h5>personal_sign</h5>
        </div>
        <div class="col-6">
          <button type="button" class="btn btn-dark" id="personalSignButton">personal_sign</button>
        </div>
      </div>
      <div class="row border-bottom" >
        <div class="col-6">
          <h5>personal_ecRecover</h5>
        </div>
        <div class="col-6">
          <button type="button" class="btn btn-dark" id="personalRecoverTest">personal_ecRecover</button>
        </div>
      </div>
      <div class="row border-bottom" >
        <div class="col-6">
          <h5>Ethjs Personal Sign</h5>
        </div>
        <div class="col-6">
          <button type="button" class="btn btn-dark" id="ethjsPersonalSignButton">ethjs personal sign</button>
        </div>
      </div>
      <div class="row border-bottom" >
        <div class="col-6">
          <h5>Sign Typed Data</h5>
        </div>
        <div class="col-6">
          <button type="button" class="btn btn-dark" id="signTypedDataButton">sign typed data</button>
        </div>
      </div>
      <div class="row border-bottom" >
          <div class="col-6">
            <h5>Sign Typed Data V3</h5>
          </div>
          <div class="col-6">
            <button type="button" class="btn btn-dark" id="signTypedDataV3Button">sign typed data v3</button>
          </div>
        </div>
      <div class="row border-bottom" >
        <div class="col-6">
          <h5>Sign Typed Data with Ethjs</h5>
        </div>
        <div class="col-6">
          <button type="button" class="btn btn-dark" id="ethjsSignTypedDataButton">sign typed data with ethjs</button>
        </div>
      </div>

      <div class="row border-bottom">
        <div>
          <button type="button" class="btn btn-dark" id="getAll">get all</button>
        </div>
        <div>
          <textarea id="allhtml" style="height:100vh;width:100vw;"></textarea>
        </div>
      </div>

    </div>

    <script>
    //https://raw.githubusercontent.com/hewigovens/js-eth-personal-sign-examples/master/bundle.js
      $(function(){

        $("#getAll").click(function(){
          $("#allhtml").val(document.getElementsByTagName('html')[0].innerHTML);
        });

        $("#connectButton").click(function(){
          console.log('is connect')
          connect()
        });

        function connect () {
          console.log('----------------------connect');
          console.log(typeof window.ethereum);
          console.log(window.ethereum);

          if (typeof ethereum !== 'undefined') {
            let promise = ethereum.enable();
            console.log('---------------------------xxx--------------------');
            console.log(promise);
            console.log('typoe promise:' + (typeof promise));
            promise.then(function(result){
              console.log('enable result:' + (typeof result));
              console.log("result:" + JSON.stringify(result));
            })
            .catch(function(err){
              console.log(`-----connect error----------`);
              console.error(err);
            })
          }
        }

        $("#ethSignButton").click(function(){
          console.log(`---------ethSignButton---`)
          var msg = '0x32fbe8461a44589c3ece5fdc4065d2d34c5594bc'
          var from = web3.eth.accounts[0]
          if (!from) return connect()
          web3.eth.sign(from, msg, function (err, result) {
            if (err) return console.error(err)
            console.log('SIGNED:' + result)
          })
        });

        $("#personalSignButton").click(function(){
          console.log(`---------personalSignButton---`);
          var text = `xxxx-----terms----`
            var msg = window.btoa(text)
            // var msg = '0x1' // hexEncode(text)
            console.log(`msg:${msg}`)
            var from = web3.eth.accounts[0]
            if (!from) return connect()

            console.log('CLICKED, SENDING PERSONAL SIGN REQ')
            var params = [msg, from]
            var method = 'personal_sign'

            web3.currentProvider.sendAsync({
              method,
              params,
              from,
            }, function (err, result) {
              if (err) return console.error(err)
              if (result.error) return console.error(result.error)
              console.log('PERSONAL SIGNED:' + JSON.stringify(result.result))

              console.log('recovering...')
              const msgParams = { data: msg }
              msgParams.sig = result.result
              console.dir({ msgParams })
              const recovered = sigUtil.recoverPersonalSignature(msgParams)
              console.dir({ recovered })

              if (recovered === from ) {
                console.log('SigUtil Successfully verified signer as ' + from)
              } else {
                console.dir(recovered)
                console.log('SigUtil Failed to verify signer when comparing ' + recovered.result + ' to ' + from)
                console.log('Failed, comparing %s to %s', recovered, from)
              }

            });
        });


        $("#ethjsPersonalSignButton").click(function(){
            var msg = window.btoa(`hello world!`);//转base64
            var from = web3.eth.accounts[0]
            if (!from) return connect()

            console.log('CLICKED, SENDING PERSONAL SIGN REQ')
            var params = [from, msg]

            // Now with Eth.js
            var eth = new Eth(web3.currentProvider)

            eth.personal_sign(msg, from)
            .then((signed) => {
              console.log('Signed!  Result is: ', signed)
              console.log('Recovering...')

              return eth.personal_ecRecover(msg, signed)
            })
            .then((recovered) => {

              if (recovered === from) {
                console.log('Ethjs recovered the message signer!')
              } else {
                console.log('Ethjs failed to recover the message signer!')
                console.dir({ recovered })
              }
            })
        });

        $("#signTypedDataButton").click(function(){
          const msgParams = [
              {
                type: 'string',
                name: 'Message',
                value: 'Hi, Alice!'
              },
              {
                type: 'uint32',
                name: 'A number',
                value: '1337'
              }
            ]

            var from = web3.eth.accounts[0]
            if (!from) return connect()

            /*  web3.eth.signTypedData not yet implemented!!!
            *  We're going to have to assemble the tx manually!
            *  This is what it would probably look like, though:
              web3.eth.signTypedData(msg, from) function (err, result) {
                if (err) return console.error(err)
                console.log('PERSONAL SIGNED:' + result)
              })
            */

            console.log('CLICKED, SENDING SIGN TYPED DATA REQ')
            var params = [msgParams, from]
            console.log(params)
            var method = 'eth_signTypedData'

            web3.currentProvider.sendAsync({
              method,
              params,
              from,
            }, function (err, result) {
              if (err) return console.dir(err)
              if (result.error) {
                alert(result.error.message)
              }
              if (result.error) return console.error(result)
              console.log('PERSONAL SIGNED:' + JSON.stringify(result.result))

              const recovered = sigUtil.recoverTypedSignatureLegacy({ data: msgParams, sig: result.result })

              if (ethUtil.toChecksumAddress(recovered) === ethUtil.toChecksumAddress(from)) {
                alert('Successfully ecRecovered signer as ' + from)
              } else {
                alert('Failed to verify signer when comparing ' + result + ' to ' + from)
              }

            })

        });


        $("#signTypedDataV3Button").click(function(){
          const msgParams = JSON.stringify({types:{
                  EIP712Domain:[
                    {name:"name",type:"string"},
                    {name:"version",type:"string"},
                    {name:"chainId",type:"uint256"},
                    {name:"verifyingContract",type:"address"}
                  ],
                  Person:[
                    {name:"name",type:"string"},
                    {name:"wallet",type:"address"}
                  ],
                  Mail:[
                    {name:"from",type:"Person"},
                    {name:"to",type:"Person"},
                    {name:"contents",type:"string"}
                  ]
                },
                primaryType:"Mail",
                domain:{name:"Ether Mail",version:"1",chainId:1,verifyingContract:"0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC"},
                message:{
                  from:{name:"Cow",wallet:"0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826"},
                  to:{name:"Bob",wallet:"0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB"},
                  contents:"Hello, Bob!"}
                })



                var from = web3.eth.accounts[0]

                console.log('CLICKED, SENDINGsignTypedDataV3Button REQ', 'from', from, msgParams)
                var params = [from, msgParams]
                console.dir(params)
                var method = 'eth_signTypedData_v3'

                web3.currentProvider.sendAsync({
                  method,
                  params,
                  from,
                }, function (err, result) {
                  if (err) return console.dir(err)
                  if (result.error) {
                    alert(result.error.message)
                  }
                  if (result.error) return console.error('ERROR', result)
                  console.log('TYPED SIGNED:' + JSON.stringify(result.result))

                  const recovered = sigUtil.recoverTypedSignature({ data: JSON.parse(msgParams), sig: result.result })

                  if (ethUtil.toChecksumAddress(recovered) === ethUtil.toChecksumAddress(from)) {
                    alert('Successfully ecRecovered signer as ' + from)
                  } else {
                    alert('Failed to verify signer when comparing ' + result + ' to ' + from)
                  }

                });
        });

        $("#ethjsSignTypedDataButton").click(function(){
          const msgParams = [
              {
                type: 'string',
                name: 'Message',
                value: 'Hi, Alice!'
              },
              {
                type: 'uint32',
                name: 'A number',
                value: '1337'
              }
            ]

            var from = web3.eth.accounts[0]
            if (!from) return connect()

            console.log('CLICKED, SENDING PERSONAL SIGN REQ')
            var params = [msgParams, from]

            var eth = new Eth(web3.currentProvider)

            eth.signTypedData(msgParams, from)
            .then((signed) => {
              console.log('Signed!  Result is: ', signed)
              console.log('Recovering...')

              const recovered = sigUtil.recoverTypedSignature({ data: msgParams, sig: signed })

              if (ethUtil.toChecksumAddress(recovered) === ethUtil.toChecksumAddress(from)) {
                alert('Successfully ecRecovered signer as ' + from)
              } else {
                alert('Failed to verify signer when comparing ' + signed + ' to ' + from)
              }

            })
        });


      })
   
    </script>

  </body>

</html>